package com.zgjkhis.modules.system.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.poi.excel.ExcelFileUtil;
import com.zgjkhis.domain.PageResult;
import com.zgjkhis.exception.ServiceException;
import com.zgjkhis.logging.aop.log.Log;
import com.zgjkhis.modules.security.security.LoginUserUtil;
import com.zgjkhis.modules.system.domain.DrugDelivery;
import com.zgjkhis.modules.system.domain.Store;
import com.zgjkhis.modules.system.domain.vo.DrugDeliveryDetailVO;
import com.zgjkhis.modules.system.domain.vo.DrugDeliveryVo;
import com.zgjkhis.modules.system.service.DrugDeliveryDetailService;
import com.zgjkhis.modules.system.service.DrugDeliveryService;
import com.zgjkhis.modules.system.service.DrugWareHousingDetailService;
import com.zgjkhis.modules.system.service.StoreService;
import com.zgjkhis.modules.system.service.dto.DrugDeliveryQueryCriteria;
import com.zgjkhis.modules.system.service.dto.DrugQueryCriteria;
import com.zgjkhis.modules.system.service.dto.DrugWareHousingDetailDto;
import com.zgjkhis.modules.system.service.dto.ValidityDrugCriteria;
import com.zgjkhis.modules.util.CharUtil;
import com.zgjkhis.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @date 2018-11-23
 */
@Api(tags = "库房管理：药品出库")
@RestController
@RequestMapping("/drugdelivery")
public class DrugDeliveryController {

    private static final String ENTITY_NAME = "drugDeliver";
    private final DrugDeliveryService drugDeliveryService;
    private final DrugDeliveryDetailService drugDeliveryDetailService;
    private final DrugWareHousingDetailService drugWareHousingDetailService;
    private final StoreService storeService;

    public DrugDeliveryController(DrugDeliveryService drugDeliveryService, DrugDeliveryDetailService drugDeliveryDetailService, DrugWareHousingDetailService drugWareHousingDetailService, StoreService storeService) {
        this.drugDeliveryService = drugDeliveryService;
        this.drugDeliveryDetailService = drugDeliveryDetailService;
        this.drugWareHousingDetailService = drugWareHousingDetailService;
        this.storeService = storeService;
    }


    @Log("新增或修改药品出库")
    @ApiOperation("新增药品出库")
    @PostMapping(value = "/add")
//    @PreAuthorize("@el.check('drugDelivery:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody DrugDelivery resources) {
//        if (resources.getId() != null) {
//            throw new ServiceException("A new "+ ENTITY_NAME +" cannot already have an ID");
//        }
        return new ResponseEntity<>(drugDeliveryService.createDrugWareHousing(resources), HttpStatus.OK);
    }


    @Log("查看药品出库")
    @GetMapping(value = "/detail")
    @ApiOperation("查看药品出库")
    //    @PreAuthorize("@el.check('drugDelivery:datail')")
    public ResponseEntity<Object> getDetail(String id) {
        if (CharUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        DrugDelivery drugDelivery = drugDeliveryService.getById(id);
        DrugDeliveryVo drugDeliveryVo = new DrugDeliveryVo();
        BeanUtil.copyProperties(drugDelivery, drugDeliveryVo);
        List<DrugDeliveryDetailVO> list = drugDeliveryDetailService.queryList(drugDelivery.getDeliveryNo());
        drugDeliveryVo.setList(list);
        Store store = storeService.getById(drugDelivery.getPharmacyId());
        drugDeliveryVo.setStoreName(store.getStoreName());
        return new ResponseEntity<>(drugDeliveryVo, HttpStatus.OK);
    }

    @Log("取消药品出库")
    @ApiOperation("取消药品出库")
    @PostMapping(value = "/update")
//    @PreAuthorize("@el.check('drugDelivery:update')")
    public ResponseEntity<Object> update(String id) {
        if (CharUtil.isEmpty(id)) {
            throw new ServiceException("出库id不能为空");
        }
        DrugDelivery drugDelivery = drugDeliveryService.getById(id);
        if (CharUtil.isEmpty(drugDelivery)) {
            throw new ServiceException("出库单子不存在");
        }
        if (drugDelivery.getStatus() != 1) {
            throw new ServiceException("订单状态处于不可以取消");
        }
        DrugDelivery delivery = new DrugDelivery();
        delivery.setId(drugDelivery.getId());
        delivery.setStatus(3);
        delivery.setCheckUserName(LoginUserUtil.getNickName());
        delivery.setCheckUserId(SecurityUtils.getUserId().toString());
        delivery.setCheckTime(new Date());
        return new ResponseEntity<>(drugDeliveryService.updateById(delivery), HttpStatus.OK);
    }

    @Log("分页查询出库信息")
    @ApiOperation("分页查询出库信息")
    @GetMapping(value = "/getList")
//    @PreAuthorize("@el.check('drugDelivery:list')")
    public ResponseEntity<PageResult<DrugDelivery>> getList(DrugDeliveryQueryCriteria criteria, Pageable pageable) {
        criteria.setPharmacyId(LoginUserUtil.getPharmId());
        return new ResponseEntity<>(drugDeliveryService.findAllByPageable(criteria, pageable), HttpStatus.OK);
    }

    @Log("分页查询入库详情清单信息")
    @ApiOperation("分页查询入库详情清单信息")
    @GetMapping(value = "/getDrugHousingDetailList")
//    @PreAuthorize("@el.check('drugDelivery:list')")
    public ResponseEntity<PageResult<DrugWareHousingDetailDto>> getDrugHousingDetailList(@ApiParam(name = "药品名称/拼音", required = true) String drugName, Pageable pageable, Integer drugType) {
        if (CharUtil.isEmpty(drugName)) {
            throw new ServiceException("药品名称/拼音不能为空");
        }
        DrugQueryCriteria criteria = new DrugQueryCriteria();
        criteria.setDrugName(drugName);
        criteria.setDrugType(drugType);
        criteria.setPharmacyId(LoginUserUtil.getPharmId());
        return new ResponseEntity<>(drugWareHousingDetailService.findAllWareDetailByPageable(criteria, pageable), HttpStatus.OK);
    }

    @Log("分页查询入库详情已过期药品清单")
    @ApiOperation("分页查询入库详情已过期药品清单")
    @GetMapping(value = "/getValidityDrugDetailList")
    public ResponseEntity getValidityDrugDetailList(ValidityDrugCriteria criteria) {
        criteria.setPharmacyId(LoginUserUtil.getPharmId());
        return new ResponseEntity<>(drugWareHousingDetailService.getValidityDrugDetailList(criteria), HttpStatus.OK);
    }

    @Log("导出出库模版")
    @ApiOperation("导出入库模版")
    @GetMapping(value = "/outTemplate")
    public void outTemplate(DrugQueryCriteria criteria, HttpServletResponse response) throws IOException {
        criteria.setPharmacyId(LoginUserUtil.getPharmId());
        drugDeliveryService.outTemplate(criteria, response);
    }

    @Log("出库导入")
    @ApiOperation("入库导入")
    @PostMapping(value = "/inTemplate")
//    @PreAuthorize("@el.check('drug:list')")
    public ResponseEntity<Object> inTemplate(@RequestParam("file") MultipartFile file, @ApiParam("出库方式") Integer deliveryType, @ApiParam("领用科室id") String collectDeptId, @ApiParam("领用人id") String collectUseId, @ApiParam("备注") String remark, @ApiParam("领用科室") String collectDeptName, @ApiParam("领用人") String collectUseName, @ApiParam("药品类型") Integer drugType) throws IOException, ParseException {
        if (file == null) {
            throw new ServiceException("请上传文件");
        }
        if (!ExcelFileUtil.isXls(file.getInputStream()) && !ExcelFileUtil.isXlsx(file.getInputStream())) {
            throw new ServiceException("请上传excel文件");
        }
        drugDeliveryService.inTemplate(file, deliveryType, collectDeptId, collectUseId, remark, collectDeptName, collectUseName, drugType);
        return new ResponseEntity<>(true, HttpStatus.OK);
    }


    @Log("导出入库单")
    @ApiOperation("导出入库单")
    @GetMapping(value = "/outDelivery")
    public void outWareHousing(String id, HttpServletResponse response) throws IOException {
        if (CharUtil.isEmpty(id)) {
            throw new ServiceException("id不能为空");
        }
        drugDeliveryService.outDelivery(id, response);
    }


}
